package com.alvin.demo.handler;

import com.alvin.demo.common.R;
import com.alvin.demo.utils.RequestUtils;
import com.alvin.demo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
    @ExceptionHandler(UnauthorizedException.class)
    public String ErrorHandler(
            UnauthorizedException e,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // 配合注解式 权限控制使用
        log.error("没有通过权限验证！");
        if (RequestUtils.isStandardUrlRequest(request)){
            return "redirect:/error/403.html";
        }
        R r = R.error(403 , "没有该操作的权限！");
        ResponseUtils.out(response, r);
        return null ;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFound(
            HttpServletRequest request,
            HttpServletResponse response,
            NoHandlerFoundException ex) throws IOException {
        log.error("请求路径不存在：{}", request.getRequestURI() );
        if (RequestUtils.isStandardUrlRequest(request)){
            return "redirect:/error/404.html";
        }
        R r = R.error(404 , "404 请求资源不存在");
        ResponseUtils.out(response, r);
        return null ;
    }

}